package battleship;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class LogInServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        System.out.println("LoginServlet: starting");

        CreateDatabase.create();
        Databasetest.addScores("Kalle", 1);

        // the username the user entered
        String username = request.getParameter("username");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        User user; String userUsername;
        int i = 0;
        // find the user if he/she exists
        while ((user = Context.users[i]) != null) {
            userUsername = user.getUsername();
            if (userUsername.equals(username)) {
                // check if user is online
                if (user.online) {
                    // return empty string to indicate that someone with that username is already online
                    out.print("");
                    out.close();
                    return;
                }
                // if user isn't online, return user's id
                user.lastSeen = new Date(); // mark user as being online now
                user.online = true;
                Context.onlineUsers.add(user);
                user.checkIfOnline(); // start heartbeat to check if user is online
                out.print(user.id);
                out.close();
                return;
            }
            i++;
        }
        // if you've reached this point, then this is the user's first visit
        // create user, add them to user list
        System.out.println("LoginS: creating a user!");
        user = new User();
        Context.users[user.id] = user;
        user.username = username;
        Context.onlineUsers.add(user);

        CreateDatabase.create();
        Databasetest.addScores("Kalle", 1);

        // return user's id
        out.print(user.id);
        out.close();

        System.out.println("LogInServlet: finished");
    }
    
}
